import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../Util/HttpGo.dart';
import 'Account/Login.dart';
import 'Home/Home.dart';

class Splash extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    FlutterSmartDialog.monitor();
    return MaterialApp(
      theme: ThemeData(
        primaryColor: MyColor.White,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      navigatorObservers: [FlutterSmartDialog.observer],
      builder: (context, child) {
        return GestureDetector(
            onTap: () {
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                FocusManager.instance.primaryFocus?.unfocus();
              }
            },
            child: MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: FlutterSmartDialog(child: child),
            ));

        //   MediaQuery(
        //   data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
        //   child: FlutterSmartDialog(child: child),
        // );
      },
      home: SplashPage(),
    );
  }
}

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _SplashPage();
  }
}

class _SplashPage extends State<SplashPage> {
  @override
  void initState() {
    openLoginPageByTimer(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: MyColor.White,
      child: LocalImage("splash.jpg", fit: BoxFit.contain),
    );
  }

  openLoginPageByTimer(BuildContext context) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Global.token = prefs.getString("token") ?? "";
    Global.studentId = prefs.getString("studentId") ?? "";
    Global.userId = prefs.getString("userId") ?? "";
    Global.userName = prefs.getString("userName") ?? "";
    const timeout = const Duration(seconds: 2);
    Timer(timeout, () {
      if (Global.token.isNotEmpty) {
        PageUtil().openReplace(context, Home());
      } else {
        PageUtil().openReplace(context, Login());
      }
    });
  }
}
